<?php

namespace app\admin\model\yxerp;

use think\Model;

class AiModel extends Model
{
    // 表名
    protected $name = 'yxerp_ai_models';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 追加属性
    protected $append = [
        'params_array'
    ];
    
    // 获取JSON参数为数组
    public function getParamsArrayAttr($value, $data)
    {
        $params = $data['params'] ?? '{}';
        return json_decode($params, true) ?: [];
    }
    
    // 设置参数
    public function setParamsAttr($value)
    {
        if (is_array($value)) {
            return json_encode($value);
        }
        return $value;
    }
    
    // 获取本地模型列表
    public static function getLocalModels()
    {
        return self::where('type', 'local')
            ->where('is_active', 1)
            ->select();
    }
    
    // 获取远程模型列表
    public static function getRemoteModels()
    {
        return self::where('type', 'remote')
            ->where('is_active', 1)
            ->select();
    }
    
    // 获取所有模型
    public static function getAllModels()
    {
        return self::where('is_active', 1)
            ->order('type, id DESC')
            ->select();
    }
    
    // 验证模型连接
    public function testConnection()
    {
        $result = [
            'success' => false,
            'message' => '未实现的测试方法',
            'data' => null
        ];
        
        // 根据模型类型执行不同的测试逻辑
        if ($this->type == 'local') {
            // 测试本地Ollama连接
            $result = $this->testOllamaConnection();
        } else if ($this->type == 'remote') {
            // 测试远程API连接
            switch ($this->provider) {
                case 'openai':
                    $result = $this->testOpenAIConnection();
                    break;
                case 'azure':
                    $result = $this->testAzureConnection();
                    break;
                case 'anthropic':
                    $result = $this->testAnthropicConnection();
                    break;
                case 'deepseek':
                    $result = $this->testDeepSeekConnection();
                    break;
                default:
                    $result = $this->testCustomAPIConnection();
            }
        }
        
        return $result;
    }
    
    // 测试Ollama连接
    protected function testOllamaConnection()
    {
        $endpoint = rtrim($this->endpoint, '/');
        $url = "{$endpoint}/api/tags";
        
        try {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200) {
                $data = json_decode($response, true);
                if (isset($data['models']) && is_array($data['models'])) {
                    return [
                        'success' => true,
                        'message' => '连接成功',
                        'data' => $data['models']
                    ];
                }
            }
            
            return [
                'success' => false,
                'message' => "连接失败: HTTP状态码 {$httpCode}",
                'data' => null
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => '连接失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
    
    // 测试OpenAI连接
    protected function testOpenAIConnection()
    {
        $endpoint = rtrim($this->endpoint ?: 'https://api.openai.com', '/');
        $url = "{$endpoint}/v1/models";
        
        try {
            $ch = curl_init($url);
            $headers = [
                'Authorization: Bearer ' . $this->api_key,
                'Content-Type: application/json'
            ];
            
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200) {
                $data = json_decode($response, true);
                if (isset($data['data']) && is_array($data['data'])) {
                    return [
                        'success' => true,
                        'message' => '连接成功',
                        'data' => $data['data']
                    ];
                }
            }
            
            return [
                'success' => false,
                'message' => "连接失败: HTTP状态码 {$httpCode}",
                'data' => null
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => '连接失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }
    
    // 测试Azure连接 (简化实现)
    protected function testAzureConnection()
    {
        return [
            'success' => true,
            'message' => '连接测试已模拟 (Azure)',
            'data' => [
                ['id' => 'gpt-35-turbo', 'name' => 'GPT-3.5 Turbo'],
                ['id' => 'gpt-4', 'name' => 'GPT-4'],
                ['id' => 'gpt-4-turbo', 'name' => 'GPT-4 Turbo'],
            ]
        ];
    }
    
    // 测试Anthropic连接 (简化实现)
    protected function testAnthropicConnection()
    {
        return [
            'success' => true,
            'message' => '连接测试已模拟 (Anthropic)',
            'data' => [
                ['id' => 'claude-1', 'name' => 'Claude 1'],
                ['id' => 'claude-2', 'name' => 'Claude 2'],
                ['id' => 'claude-instant-1', 'name' => 'Claude Instant'],
            ]
        ];
    }
    
    // 测试DeepSeek连接 (简化实现)
    protected function testDeepSeekConnection()
    {
        return [
            'success' => true,
            'message' => '连接测试已模拟 (DeepSeek)',
            'data' => [
                ['id' => 'deepseek-chat', 'name' => 'DeepSeek Chat'],
                ['id' => 'deepseek-coder', 'name' => 'DeepSeek Coder'],
            ]
        ];
    }
    
    // 测试自定义API连接 (简化实现)
    protected function testCustomAPIConnection()
    {
        return [
            'success' => true,
            'message' => '连接测试已模拟 (自定义API)',
            'data' => []
        ];
    }
} 